package com.jz.netthings.application.sample.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jz.netthings.appengine.baseData.ProviderData;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.mapper.ProviderDataMapper;
import com.jz.netthings.appengine.mapper.ProviderInfoMapper;
import com.jz.netthings.appengine.queue.MachineMgr;
import com.jz.netthings.appengine.queue.ProviderQueue;
import com.jz.netthings.appengine.support.BeanSupport;
import com.jz.netthings.application.bodyCheck.bean.BodyCheck;
import com.jz.netthings.application.bodyCheck.bean.MyPage;
import com.jz.netthings.application.bodyCheck.mapper.mysql.BodyCheckMapper;
import com.jz.netthings.application.providerCreate.bean.ProviderXp;
import com.jz.netthings.application.providerCreate.mapper.mysql.ProviderXpMapper;
import com.jz.netthings.application.providerReg.bean.ProviderReg;
import com.jz.netthings.application.providerReg.mapper.mysql.ProviderRegMapper;
import com.jz.netthings.application.sample.bean.*;
import com.jz.netthings.application.sample.mapper.AssayReagentMapper;
import com.jz.netthings.application.sample.mapper.AssayXhdbReagentMapper;
import com.jz.netthings.application.sample.mapper.PlasmaSamplesMapper;
import com.jz.netthings.application.sample.service.PlasmaSamplesService;
import com.jz.netthings.application.sample.utils.JsonUtils;
import com.jz.netthings.application.utils.AppUtils;
import com.jz.netthings.bean.system.JyCode;
import com.jz.netthings.bean.system.JyUser;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.system.mapper.mysql.JyCodeMapper;
import com.jz.netthings.system.mapper.mysql.JyUserMapper;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import net.sf.jsqlparser.statement.select.Limit;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzf
 * @since 2019-03-12
 */
@Service
public class PlasmaSamplesServiceImpl extends ServiceImpl<PlasmaSamplesMapper, PlasmaSamples> implements PlasmaSamplesService {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private PlasmaSamplesMapper plasmaSamplesMapper;
    @Autowired
    private JyUserMapper jyUserMapper;
    @Autowired
    private ProviderInfoMapper providerInfoMapper;
    @Autowired
    private ProviderDataMapper providerDataMapper;
    @Autowired
    private ProviderQueue providerQueue;
    @Autowired
    ProviderXpMapper providerXpMapper;
    @Autowired
    JyCodeMapper jyCodeMapper;
    @Autowired
    BodyCheckMapper bodyCheckMapper;
    @Autowired
    ProviderRegMapper providerRegMapper;;

    /**
     * engine模块的IP和端口
     */
    @Value("${netty.engine.ipAddress}")
    private String engineIp;
    @Value("${netty.engine.serverPort}")
    private String engineServerPort;

    @Override
    public MyPage<PlasmaSamples> queryCurrentDays(Integer currentPage,Integer pageSize) throws AdscmSystemException {
        MyPage<PlasmaSamples> myPage=new MyPage<>();
        if (currentPage!=0){
            if (currentPage==1){
                currentPage=0;
            }else {
                currentPage=(currentPage*pageSize)-1;
            }
        }
        String currentDays = AdscmDateUtils.getNowOnlyDateFomat2(new Date());
        List<PlasmaSamples> plasmaSamples = plasmaSamplesMapper.selectCurrentDaysByPage(currentPage, pageSize,currentDays);
        for (PlasmaSamples record : plasmaSamples) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getCreateNurse(),null)){
                record.setCreateNurseName(jyUserMapper.selectById(record.getCreateNurse()).getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProviderNo(),null)){
                ProviderInfo providerInfo = providerInfoMapper.selectById(record.getProviderNo());
                if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
                    record.setName(providerInfo.getName());
                }
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getRecodeStatus(),null)){
                record.setRecodeStatusName(plasmaSamplesMapper.getCodeData("16",String.valueOf(record.getRecodeStatus())));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProteinLevel(),null)){
                record.setProteinLevel(plasmaSamplesMapper.getCodeData("19",record.getProteinLevel()));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getHemoglobinLevel(),null)){
                record.setHemoglobinLevelName(plasmaSamplesMapper.getCodeData("17",record.getHemoglobinLevel()));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getInspectionRecodePerson(),null)){
                record.setInspectionRecodePersonName(jyUserMapper.selectById(record.getInspectionRecodePerson()).getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getInspectionResult(),null)){
                record.setInspectionResultName(plasmaSamplesMapper.getCodeData("18",String.valueOf(record.getInspectionResult())));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProviderNo(),null)){
                ProviderInfo providerInfo = providerInfoMapper.selectById(record.getProviderNo());
                if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
                    record.setCardId(providerInfo.getCardId());
                }else {
                    throw new AdscmSystemException("没有查到对应的卡号");
                }

            }
        }

        myPage.setItems(plasmaSamples);
        myPage.setTotal(plasmaSamplesMapper.queryCurrentDaysCount(currentDays));
        return myPage;
    }
    @Override
    public MyPage<PlasmaSamples> queryAll(Integer currentPage,Integer pageSize) throws AdscmSystemException {
        MyPage<PlasmaSamples> myPage=new MyPage<>();
        if (currentPage!=0){
            if (currentPage==1){
                currentPage=0;
            }else {
                currentPage=(currentPage*pageSize)-1;
            }
        }
        List<PlasmaSamples> plasmaSamples = plasmaSamplesMapper.selectByPage(currentPage, pageSize);
        for (PlasmaSamples record : plasmaSamples) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getCreateNurse(),null)){
                record.setCreateNurseName(jyUserMapper.selectById(record.getCreateNurse()).getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProviderNo(),null)){
                ProviderInfo providerInfo = providerInfoMapper.selectById(record.getProviderNo());
                if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
                    record.setName(providerInfo.getName());
                }
//                else {
//                    throw new AdscmSystemException("没有查询到该浆员的建档信息");
//                }
//                record.setName(jyUserMapper.selectById(record.getProviderNo()).getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getRecodeStatus(),null)){
                record.setRecodeStatusName(plasmaSamplesMapper.getCodeData("16",String.valueOf(record.getRecodeStatus())));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProteinLevel(),null)){
                record.setProteinLevel(plasmaSamplesMapper.getCodeData("19",record.getProteinLevel()));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getHemoglobinLevel(),null)){
                record.setHemoglobinLevelName(plasmaSamplesMapper.getCodeData("17",record.getHemoglobinLevel()));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getInspectionRecodePerson(),null)){
                record.setInspectionRecodePersonName(jyUserMapper.selectById(record.getInspectionRecodePerson()).getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getInspectionResult(),null)){
                record.setInspectionResultName(plasmaSamplesMapper.getCodeData("18",String.valueOf(record.getInspectionResult())));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProviderNo(),null)){
                ProviderInfo providerInfo = providerInfoMapper.selectById(record.getProviderNo());
                if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
                    record.setCardId(providerInfo.getCardId());
                }else {
                    throw new AdscmSystemException("没有查到对应的卡号");
                }

            }
        }

        myPage.setItems(plasmaSamples);
        myPage.setTotal(plasmaSamplesMapper.queryCount());
//        Page<PlasmaSamples> page=new Page<>(currentPage,pageSize);
//        Wrapper<PlasmaSamples> plasmaSamplesWrapper=new EntityWrapper<>();
//        plasmaSamplesWrapper.ne("recodeStatus",2);
//        plasmaSamplesWrapper.orderBy("sampleNo,recodeStatus");
//        Page<PlasmaSamples> page1 = selectPage(page, plasmaSamplesWrapper);
//        List<PlasmaSamples> records = page1.getRecords();
/*        for (PlasmaSamples record : records) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getCreateNurse(),null)){
                record.setCreateNurseName(jyUserMapper.selectById(record.getCreateNurse()).getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getRecodeStatus(),null)){
                record.setRecodeStatusName(plasmaSamplesMapper.getCodeData("16",String.valueOf(record.getRecodeStatus())));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProteinLevel(),null)){
                record.setProteinLevel(plasmaSamplesMapper.getCodeData("19",record.getProteinLevel()));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getHemoglobinLevel(),null)){
                record.setHemoglobinLevelName(plasmaSamplesMapper.getCodeData("17",record.getHemoglobinLevel()));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getInspectionRecodePerson(),null)){
                record.setInspectionRecodePersonName(jyUserMapper.selectById(record.getInspectionRecodePerson()).getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getInspectionResult(),null)){
                record.setInspectionResultName(plasmaSamplesMapper.getCodeData("18",String.valueOf(record.getInspectionResult())));
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProviderNo(),null)){
                ProviderInfo providerInfo = providerInfoMapper.selectById(record.getProviderNo());
                if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
                    record.setCardId(providerInfo.getCardId());
                }else {
                    throw new AdscmSystemException("没有查到对应的卡号");
                }

            }
        }*/
//        page1.setTotal(selectCount(null));
        return myPage;
    }

    @Override
    public Page<PlasmaSamples> queryByNameAndNo(String name,String smallNo,Integer currentPage, Integer pageSize, String type,String time) throws AdscmSystemException {
        Page<PlasmaSamples> page =new Page<>(currentPage,pageSize);
        Wrapper<PlasmaSamples> wrapper=new EntityWrapper<>();

        boolean isCurrentDay = true;//是否只查询当天的，如果有时间条件的，则不是查询当天


        if (AdscmBaseUtils.getInstance().isNotEmpty(name,null)){
            wrapper.like("name",name);
            isCurrentDay = false;
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(smallNo,null)){
            wrapper.eq("sampleNo",smallNo);
            isCurrentDay = false;
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(type,null)){
            wrapper.eq("sampleType",type);
            isCurrentDay = false;
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(time,null)){
            time = AdscmDateUtils.getNowOnlyDateFomat2(AdscmDateUtils.parseDate(time));
            wrapper.like("sampleNo",time);
            isCurrentDay = false;
        }

        if (isCurrentDay){
            wrapper.like("sampleNo",AdscmDateUtils.getNowOnlyDateFomat2(new Date()));
        }


//        if (null != name){
//            wrapper.like("name",name).or().like("sampleNo",smallNo).or().eq("sampleType",type).or().like("recodeTime",time);
//        }
//        if (null==name && null ==smallNo){
//            throw new AdscmSystemException("不能进行空参查询");
//        }
//        Page<PlasmaSamples> page1 = super.selectPage(page, wrapper);
//        page1.setTotal(super.selectCount(wrapper));
//        return page1;

        Page<PlasmaSamples> samplesPage = super.selectPage(page, wrapper);
        int count = super.selectCount(wrapper);
        samplesPage.setTotal(count);
        List<PlasmaSamples> records = samplesPage.getRecords();
        if (records != null && records.size()>0){

            for (PlasmaSamples record : records) {
                List<JyCode> codeType = jyCodeMapper.getJyCodeByCodeType("qualifiedStatus");
                for (JyCode jyCode : codeType) {
                    if (record.getInspectionResult() != null && jyCode.getCode().equals(record.getInspectionResult().toString())){
                        record.setInspectionResultName(jyCode.getName());
                        break;
                    }

                }
                codeType = jyCodeMapper.getJyCodeByCodeType("simpleRecodeStatus");
                for (JyCode jyCode : codeType) {
                    if (record.getRecodeStatus() != null && jyCode.getCode().equals(record.getRecodeStatus().toString())){
                        record.setRecodeStatusName(jyCode.getName());
                        break;
                    }

                }

                String person = record.getInspectionRecodePerson();
                if (AdscmBaseUtils.getInstance().isNotEmpty(person,null)){
                    JyUser user = jyUserMapper.selectById(new Integer(person));
                    if (user != null){
                        record.setInspectionRecodePersonName(user.getName());
                    }
                }

            }

        }

        return samplesPage;
    }

    @Override
    public Integer updateAll(String plasmaSamples,JyUser user) throws AdscmSystemException{
        PlasmaSamples parse = JsonUtils.parse(plasmaSamples, PlasmaSamples.class);
        if (AdscmBaseUtils.getInstance().isNotEmpty(parse.getSerumProteinLevel(),null)){
            parse.setZsykdz(Integer.valueOf(parse.getSerumProteinLevel())*0.1f);
        }
        ProviderInfo providerInfo=null;
        String bloodType=null;

        if (AdscmBaseUtils.getInstance().isNotEmpty(parse.getProviderNo(),null)){
            providerInfo = providerInfoMapper.selectById(parse.getProviderNo());
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getCardId(),null)){
                ProviderData providerData = providerQueue.getByProviderNo(providerInfo.getCardId());
                if (providerInfo.getCardId().startsWith("R")){

                    boolean flag = true;
                    //要先判断胸片、体检是否合格
                    if (providerData.isNeedXp()){
                        Wrapper<ProviderXp> providerXpWrapper =new EntityWrapper<>();
                        providerXpWrapper.eq("providerNo",providerInfo.getId());
                        providerXpWrapper.orderBy("validDate",false);
                        List<ProviderXp> providerXps = providerXpMapper.selectList(providerXpWrapper);
                        if (providerXps!=null&&providerXps.size()>0){
                            ProviderXp providerXp = providerXps.get(0);
                            //胸片记录已经过了有效期提示拍胸片
                            if (new Date().getTime()>providerXp.getValidDate().getTime()){
                                flag = false;
                            }
                            //胸片不合格
                            if ("0".equals(providerXp.getResult())){
                                flag = false;
                            }
                        }else{
                            flag = false;
                        }
                    }

                    //体检
                    if (AdscmBaseUtils.getInstance().isNotEmpty(providerData.isBodyIsPass(),null)){
                        if (!providerData.isBodyIsPass()){
                            flag = false;
                        }
                    }else{
                        flag = false;
                    }


                    if(flag && parse.getInspectionResult()==1){
                        int num=1;
//                        if ("0".equals(parse.getBloodType())){
//                            bloodType="1";
//                        }else if ("1".equals(parse.getBloodType())){
//                            bloodType="2";
//                        }else if ("3".equals(parse.getBloodType())){
//                            bloodType="3";
//                        }else if ("4".equals(parse.getBloodType())){
//                            bloodType="4";
//                        }
                        bloodType = parse.getBloodType();
                        Wrapper<ProviderInfo> providerInfoWrapper=new EntityWrapper<>();
                        providerInfoWrapper.like("cardId",bloodType, SqlLike.RIGHT).orderBy("cardId",false);
                        providerInfoWrapper.last("limit 1");
                        List<ProviderInfo> providerInfoList = providerInfoMapper.selectList(providerInfoWrapper);
                        if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfoList,null)){
//                            ProviderInfo providerInfo1=new ProviderInfo();
                            Integer tmp = Integer.valueOf(providerInfoList.get(0).getCardId())+1;
                            providerInfo.setCardId(String.valueOf(tmp));
                            providerInfo.setBloodType(bloodType);
//                            providerInfo1.setId(Long.valueOf(parse.getProviderNo()));
                            providerInfoMapper.updateById(providerInfo);
                        }

                    }
                }else{
                    //不是临时卡号
                }
                providerData.setCurrentStatus(5);
                providerData.setAssayIsPass(parse.getInspectionResult()==1 ? true:false);
                providerData.setAssayPassTime(new Date());
                providerData.setAssayId(parse.getRecodeNo());
                providerData.setProviderNo(providerInfo.getCardId());
                providerDataMapper.updateById(providerData);
//                MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(providerData,null));
                AppUtils.sendMsgToAllotCtxs(providerData,"http://"+engineIp+":"+engineServerPort);
                //

                if (parse.getInspectionResult()!=1){
                    providerInfo.setRefuseDate(new Date());
                    providerInfo.setRefuseReason(parse.getRefuseReason());
                    providerInfo.setAssayResult(0);
                    providerInfo.setPlasmaType(0);
                    providerInfo.setProviderState(2);
                    providerInfoMapper.updateById(providerInfo);

                    parse.setYm(0);
                }else{
                    parse.setYm(1);
                }

            }
            //
        }



//        if (parse.getSampleType()==0){
//            if (parse.getInspectionResult()==0){
//                if (AdscmBaseUtils.getInstance().isNotEmpty(parse.getProviderNo(),null)){
//                    providerInfo = providerInfoMapper.selectById(parse.getProviderNo());
//
//                    if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
//                        if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getCardId(),null)){
//                            if (providerInfo.getCardId().startsWith("R")){
//                                int num=1;
//                                if ("0".equals(providerInfo.getBloodType())){
//                                    bloodType="1";
//                                }else if ("1".equals(providerInfo.getBloodType())){
//                                    bloodType="2";
//                                }else if ("3".equals(providerInfo.getBloodType())){
//                                    bloodType="3";
//                                }else if ("4".equals(providerInfo.getBloodType())){
//                                    bloodType="4";
//                                }
//                                Wrapper<ProviderInfo> providerInfoWrapper=new EntityWrapper<>();
//                                providerInfoWrapper.like("cardId",bloodType, SqlLike.RIGHT).orderBy("cardId",false);
//                                providerInfoWrapper.last("limit 1");
//                                List<ProviderInfo> providerInfoList = providerInfoMapper.selectList(providerInfoWrapper);
//                                if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfoList,null)){
//                                    ProviderInfo providerInfo1=new ProviderInfo();
//                                    Integer tmp = Integer.valueOf(providerInfoList.get(0).getCardId())+1;
//                                    providerInfo1.setCardId(String.valueOf(tmp));
//                                    providerInfo1.setId(Long.valueOf(parse.getProviderNo()));
//                                    providerInfoMapper.updateById(providerInfo1);
//                                }
//                            }
//                        }
//
//                    }else {
//                        throw new AdscmSystemException("没有查到该浆员的建档信息");
//                    }
//                }
//                ProviderData providerData=new ProviderData();
//                providerData.setCurrentStatus(5);
//                providerData.setAssayIsPass(true);
//                providerData.setAssayId(parse.getRecodeNo());
//                providerData.setProviderId(Long.valueOf(parse.getProviderNo()));
//                providerDataMapper.updateById(providerData);
//                MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(providerData,null));
//            }else {
//                providerInfo.setRefuseDate(new Date());
//                providerInfo.setAssayResult(1);
//                providerInfo.setPlasmaType(0);
//                providerInfo.setProviderState(2);
//                providerInfo.setId(Long.valueOf(parse.getProviderNo()));
//                providerInfoMapper.updateById(providerInfo);
//            }
//        }
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyy-MM-dd");
        if (AdscmBaseUtils.getInstance().isNotEmpty(parse.getInspectionResult(),null)){
            parse.setMODIFY_TIME(dateFormat.format(new Date()));
            parse.setMODIFY_TIME(dateFormat1.format(new Date()));
        }
        if (user != null){
            parse.setCreateNurse(user.getId()+"");
        }
        return plasmaSamplesMapper.updateById(parse);
    }

    @Override
    public Integer updateAll(PlasmaSamples parse,JyUser user) throws AdscmSystemException{
//        PlasmaSamples parse = JsonUtils.parse(plasmaSamples, PlasmaSamples.class);
        if (AdscmBaseUtils.getInstance().isNotEmpty(parse.getSerumProteinLevel(),null)){
            parse.setZsykdz(Integer.valueOf(parse.getSerumProteinLevel())*0.1f);
        }
        ProviderInfo providerInfo=null;
        String bloodType=null;

        if (AdscmBaseUtils.getInstance().isNotEmpty(parse.getProviderNo(),null)){
            providerInfo = providerInfoMapper.selectById(parse.getProviderNo());
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getCardId(),null)){
                ProviderData providerData = providerQueue.getByProviderNo(providerInfo.getCardId());
                if (providerInfo.getCardId().startsWith("R")){

                    boolean flag = true;
                    //要先判断胸片、体检是否合格
                    ProviderXp providerXp = null;
                    if (providerData.isNeedXp()){
                        Wrapper<ProviderXp> providerXpWrapper =new EntityWrapper<>();
                        providerXpWrapper.eq("providerNo",providerInfo.getId());
                        providerXpWrapper.orderBy("validDate",false);
                        List<ProviderXp> providerXps = providerXpMapper.selectList(providerXpWrapper);
                        if (providerXps!=null&&providerXps.size()>0){
                            providerXp = providerXps.get(0);
                            //胸片记录已经过了有效期提示拍胸片
                            if (new Date().getTime()>providerXp.getValidDate().getTime()){
                                flag = false;
                            }
                            //胸片不合格
                            if ("0".equals(providerXp.getResult())){
                                flag = false;
                            }
                        }else{
                            flag = false;
                        }
                    }

                    //体检
                    if (AdscmBaseUtils.getInstance().isNotEmpty(providerData.isBodyIsPass(),null)){
                        if (!providerData.isBodyIsPass()){
                            flag = false;
                        }
                    }else{
                        flag = false;
                    }


                    if(flag && parse.getInspectionResult()==1){
                        int num=1;
//                        if ("0".equals(parse.getBloodType())){
//                            bloodType="1";
//                        }else if ("1".equals(parse.getBloodType())){
//                            bloodType="2";
//                        }else if ("3".equals(parse.getBloodType())){
//                            bloodType="3";
//                        }else if ("4".equals(parse.getBloodType())){
//                            bloodType="4";
//                        }
                        bloodType = parse.getBloodType();
                        Wrapper<ProviderInfo> providerInfoWrapper=new EntityWrapper<>();
                        providerInfoWrapper.like("cardId",bloodType, SqlLike.RIGHT).orderBy("cardId",false);
                        providerInfoWrapper.last("limit 1");
                        List<ProviderInfo> providerInfoList = providerInfoMapper.selectList(providerInfoWrapper);
                        if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfoList,null)){
//                            ProviderInfo providerInfo1=new ProviderInfo();
                            Integer tmp = Integer.valueOf(providerInfoList.get(0).getCardId())+1;
                            providerInfo.setCardId(String.valueOf(tmp));
                            providerInfo.setBloodType(bloodType);
//                            providerInfo1.setId(Long.valueOf(parse.getProviderNo()));
                            providerInfo.setModifyTime(new Date());
                            providerInfoMapper.updateById(providerInfo);

                            //登记
//                            ProviderReg providerRegister = new ProviderReg();
//                            providerRegister.setRegisterNo(providerData.getRegisterNo());
//                            providerRegister.setIdNo(providerData.getIdNo());
                            Wrapper<ProviderReg> wrapper = new EntityWrapper<>();
                            wrapper.eq("registerNo",providerData.getRegisterNo());
                            wrapper.eq("idNo",providerData.getIdNo());
                            List<ProviderReg> regs = providerRegMapper.selectList(wrapper);//.getProviderRegister(providerRegister);
                            if (regs != null && regs.size()>0){
                                ProviderReg reg = regs.get(0);
                                reg.setModifyTime(new Date());
                                providerRegMapper.updateById(reg);
                            }
                            //体检

                            BodyCheck bodyCheck = bodyCheckMapper.selectById(providerData.getBodyCheckId());
                            if (bodyCheck != null){
                                bodyCheck.setMODIFY_TIME(AdscmDateUtils.getDateFomat(new Date()));
                                bodyCheckMapper.updateById(bodyCheck);
                            }

                            //胸片
                            if (providerXp == null){
                                Wrapper<ProviderXp> providerXpWrapper =new EntityWrapper<>();
                                providerXpWrapper.eq("providerNo",providerInfo.getId());
                                providerXpWrapper.orderBy("validDate",false);
                                List<ProviderXp> providerXps = providerXpMapper.selectList(providerXpWrapper);
                                if (providerXps!=null&&providerXps.size()>0) {
                                    providerXp = providerXps.get(0);
                                }
                            }
                            providerXp.setMODIFY_TIME(AdscmDateUtils.getDateFomat(new Date()));
                            providerXpMapper.updateById(providerXp);
                        }

                    }
                }else{
                    //不是临时卡号
                }

                if (providerData != null){
                    //当天的
                    providerData.setCurrentStatus(5);
                    providerData.setAssayIsPass(parse.getInspectionResult()==1 ? true:false);
                    providerData.setAssayPassTime(new Date());
                    providerData.setAssayId(parse.getRecodeNo());
                    providerData.setProviderNo(providerInfo.getCardId());
                    providerDataMapper.updateById(providerData);
//                    MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(providerData,null));
                    AppUtils.sendMsgToAllotCtxs(providerData,"http://"+engineIp+":"+engineServerPort);
                    //
                }

                if (parse.getInspectionResult()!=1){
                    providerInfo.setRefuseDate(new Date());
                    providerInfo.setRefuseReason(parse.getRefuseReason());
                    providerInfo.setAssayResult(0);
                    providerInfo.setPlasmaType(0);
                    providerInfo.setProviderState(2);
                    providerInfoMapper.updateById(providerInfo);

                    parse.setYm(0);
                }else{
                    parse.setYm(1);
                }

            }
            //
        }



//        if (parse.getSampleType()==0){
//            if (parse.getInspectionResult()==0){
//                if (AdscmBaseUtils.getInstance().isNotEmpty(parse.getProviderNo(),null)){
//                    providerInfo = providerInfoMapper.selectById(parse.getProviderNo());
//
//                    if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
//                        if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo.getCardId(),null)){
//                            if (providerInfo.getCardId().startsWith("R")){
//                                int num=1;
//                                if ("0".equals(providerInfo.getBloodType())){
//                                    bloodType="1";
//                                }else if ("1".equals(providerInfo.getBloodType())){
//                                    bloodType="2";
//                                }else if ("3".equals(providerInfo.getBloodType())){
//                                    bloodType="3";
//                                }else if ("4".equals(providerInfo.getBloodType())){
//                                    bloodType="4";
//                                }
//                                Wrapper<ProviderInfo> providerInfoWrapper=new EntityWrapper<>();
//                                providerInfoWrapper.like("cardId",bloodType, SqlLike.RIGHT).orderBy("cardId",false);
//                                providerInfoWrapper.last("limit 1");
//                                List<ProviderInfo> providerInfoList = providerInfoMapper.selectList(providerInfoWrapper);
//                                if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfoList,null)){
//                                    ProviderInfo providerInfo1=new ProviderInfo();
//                                    Integer tmp = Integer.valueOf(providerInfoList.get(0).getCardId())+1;
//                                    providerInfo1.setCardId(String.valueOf(tmp));
//                                    providerInfo1.setId(Long.valueOf(parse.getProviderNo()));
//                                    providerInfoMapper.updateById(providerInfo1);
//                                }
//                            }
//                        }
//
//                    }else {
//                        throw new AdscmSystemException("没有查到该浆员的建档信息");
//                    }
//                }
//                ProviderData providerData=new ProviderData();
//                providerData.setCurrentStatus(5);
//                providerData.setAssayIsPass(true);
//                providerData.setAssayId(parse.getRecodeNo());
//                providerData.setProviderId(Long.valueOf(parse.getProviderNo()));
//                providerDataMapper.updateById(providerData);
//                MachineMgr.getInstance().sendMsgToAllotCtxs( BeanSupport.loadToAllotMsg(providerData,null));
//            }else {
//                providerInfo.setRefuseDate(new Date());
//                providerInfo.setAssayResult(1);
//                providerInfo.setPlasmaType(0);
//                providerInfo.setProviderState(2);
//                providerInfo.setId(Long.valueOf(parse.getProviderNo()));
//                providerInfoMapper.updateById(providerInfo);
//            }
//        }
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyy-MM-dd");
        if (AdscmBaseUtils.getInstance().isNotEmpty(parse.getInspectionResult(),null)){
            parse.setMODIFY_TIME(dateFormat.format(new Date()));
            parse.setSYNDATE(dateFormat1.format(new Date()));
        }
        if (user != null){
            parse.setCreateNurse(user.getId()+"");
            parse.setInspectionRecodePerson(user.getId()+"");
        }
        parse.setRecodeStatus(1);
        parse.setRecodeEndTime(new Date());
        return plasmaSamplesMapper.updateById(parse);
    }

    @Override
    public PlasmaSamples selectPlasmaSampleByProviderNo(String probiderNo) throws AdscmSystemException {
        PlasmaSamples plasmaSample= new PlasmaSamples();
        Wrapper<PlasmaSamples> wrapper = new EntityWrapper<>();
        wrapper.eq("providerNo",probiderNo);
        wrapper.orderBy("recodeTime",false);
        List<PlasmaSamples> plasmaSamples = super.selectList(wrapper);
        if (plasmaSamples.size()>0){
            plasmaSample=plasmaSamples.get(0);
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getCreateNurse(),null)){
            plasmaSample.setCreateNurseName(jyUserMapper.selectById(plasmaSample.getCreateNurse()).getName());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getRecodeStatus(),null)){
            plasmaSample.setRecodeStatusName(plasmaSamplesMapper.getCodeData("16",String.valueOf(plasmaSample.getRecodeStatus())));
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getProteinLevel(),null)){
            plasmaSample.setProteinLevel(plasmaSamplesMapper.getCodeData("19",plasmaSample.getProteinLevel()));
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getHemoglobinLevel(),null)){
            plasmaSample.setHemoglobinLevelName(plasmaSamplesMapper.getCodeData("17",plasmaSample.getHemoglobinLevel()));
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getInspectionRecodePerson(),null)){
            plasmaSample.setInspectionRecodePersonName(jyUserMapper.selectById(plasmaSample.getInspectionRecodePerson()).getName());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getInspectionResult(),null)){
            plasmaSample.setInspectionResultName(plasmaSamplesMapper.getCodeData("18",String.valueOf(plasmaSample.getInspectionResult())));
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(plasmaSample.getProviderNo(),null)){
            ProviderInfo providerInfo = providerInfoMapper.selectById(plasmaSample.getProviderNo());
            if (AdscmBaseUtils.getInstance().isNotEmpty(providerInfo,null)){
                plasmaSample.setCardId(providerInfo.getCardId());
            }else {
                throw new AdscmSystemException("没有查到对应的卡号");
            }

        }

        return plasmaSample;
    }

    @Value("${jz.unitName}")
    private String unitName;
    @Value("${jz.print.xhdbhl}")
    private String xhdbhl;
    @Value("${jz.print.xhdbjc}")
    private String xhdbjc;
    @Value("${jz.print.gjzhjjl}")
    private String gjzhjjl;
    @Value("${jz.print.lstbz.male}")
    private String lstbzMale;
    @Value("${jz.print.lstbz.famale}")
    private String lstbzFamale;

    @Autowired
    AssayReagentMapper assayReagentMapper;
    @Autowired
    AssayXhdbReagentMapper assayXhdbReagentMapper;

    @Override
    public AssayPrintSupport selectPrintList(String date, int printType) throws AdscmSystemException {

        AssayPrintSupport assayPrintSupport = new AssayPrintSupport();
        //打印类型 1：血红蛋白含量，2：血红蛋白检测，3：化检记录表
        if (printType == 1){
            logger.info("打印类型：血红蛋白含量");
            assayPrintSupport.setFormHeader(unitName + xhdbhl);
            assayPrintSupport.setAssayDate(date);
            assayPrintSupport.setLstbzMale(lstbzMale);
            assayPrintSupport.setLstbzFaMale(lstbzFamale);

            List<AssayXhdbReagent> reagentList = assayXhdbReagentMapper.selectList(null);
            if (reagentList != null && reagentList.size()>0){
                assayPrintSupport.setXhdbReagent(reagentList.get(0));
            }
            /**
             * 血红蛋白含量列表
             */
            String assayDate = AdscmDateUtils.getNowOnlyDateFomat2(AdscmDateUtils.parseDate(date));
            List<XhdbSupport> xhdbList = plasmaSamplesMapper.selectXhdbByAssayDate(assayDate);
            assayPrintSupport.setXhdbList(xhdbList);

            this.setCount(assayPrintSupport,assayDate);

        }else if (printType == 2){
            logger.info("打印类型：血红蛋白检测");
            assayPrintSupport.setFormHeader(unitName + xhdbjc);
            assayPrintSupport.setAssayDate(date);
            String assayDate = AdscmDateUtils.getNowOnlyDateFomat2(AdscmDateUtils.parseDate(date));
            List<XhdbSupport> xhdbList = plasmaSamplesMapper.selectXhdbByAssayDate(assayDate);
            assayPrintSupport.setXhdbList(xhdbList);

        }else {
            logger.info("打印类型：化检记录表");
            assayPrintSupport.setFormHeader(unitName + gjzhjjl);
            assayPrintSupport.setAssayDate(date);
            assayPrintSupport.setSendAssayDate(date);
            String assayDate = AdscmDateUtils.getNowOnlyDateFomat2(AdscmDateUtils.parseDate(date));
            this.setCount(assayPrintSupport,assayDate);

            /**
             * 化检结果详情列表
             */
            List<JyCode> assayResult = jyCodeMapper.getJyCodeByCodeType("inspectionResult");//化检结果，阴性/阳性
            Map<String ,JyCode> assayMap = new HashMap<>();
            for (JyCode jyCode : assayResult) {
                assayMap.put(jyCode.getCode(),jyCode);
            }
            List<JyCode> bloodType = jyCodeMapper.getJyCodeByCodeType("bloodType");//血型
            Map<String ,JyCode> bloodMap = new HashMap<>();
            for (JyCode jyCode : bloodType) {
                bloodMap.put(jyCode.getCode(),jyCode);
            }
            List<JyCode> altResult = jyCodeMapper.getJyCodeByCodeType("ALTResult");//
            Map<String ,JyCode> altMap = new HashMap<>();
            for (JyCode jyCode : altResult) {
                altMap.put(jyCode.getCode(),jyCode);
            }

            List<AssayResultPrintSupport> assayResultList = plasmaSamplesMapper.selectAssayResultList(assayDate);
            if (assayResultList != null && assayResultList.size()>0){
                for (AssayResultPrintSupport arl : assayResultList) {
                    arl.setPlasmaType("普通");
                    String bt = arl.getBloodType();
                    if(AdscmBaseUtils.getInstance().isNotEmpty(bt,null)){
                        JyCode code = bloodMap.get(bt);
                        if (code != null) {
                            arl.setBloodType(code.getName());
                        }
                    }
                    ////////////////////////////////////////
                    String hbsag = arl.getHbsag();
                    if(AdscmBaseUtils.getInstance().isNotEmpty(hbsag,null)){
                        JyCode code = assayMap.get(hbsag);
                        if (code != null) {
                            arl.setHbsag(code.getName());
                        }
                    }
                    ////////////////////////////////////////
                    String hcv = arl.getHcv();
                    if(AdscmBaseUtils.getInstance().isNotEmpty(hcv,null)){
                        JyCode code = assayMap.get(hcv);
                        if (code != null) {
                            arl.setHcv(code.getName());
                        }
                    }
                    ////////////////////////////////////////
                    String hiv = arl.getHiv();
                    if(AdscmBaseUtils.getInstance().isNotEmpty(hiv,null)){
                        JyCode code = assayMap.get(hiv);
                        if (code != null) {
                            arl.setHiv(code.getName());
                        }
                    }
                    ////////////////////////////////////////
                    String syphilis = arl.getSyphilis();
                    if(AdscmBaseUtils.getInstance().isNotEmpty(syphilis,null)){
                        JyCode code = assayMap.get(syphilis);
                        if (code != null) {
                            arl.setSyphilis(code.getName());
                        }
                    }
                    ////////////////////////////////////////
                    String alt = arl.getAlt();
                    if(AdscmBaseUtils.getInstance().isNotEmpty(alt,null)){
                        JyCode code = altMap.get(alt);
                        if (code != null){
                            arl.setAlt(code.getName());
                        }
                    }
                    ////////////////////////////////////////
                    String qxbz = arl.getQxbz();
                    if(AdscmBaseUtils.getInstance().isNotEmpty(qxbz,null)){
                        if ("1".equals(qxbz)){
                            arl.setQxbz("合格");
                        }else{
                            arl.setQxbz("不合格");
                        }
                    }
                    ////////////////////////////////////////
                    String checkResult = arl.getCheckResult();
                    if(AdscmBaseUtils.getInstance().isNotEmpty(checkResult,null)){
                        if ("1".equals(checkResult)){
                            arl.setCheckResult("合格");
                        }else{
                            arl.setCheckResult("不合格");
                        }
                    }

                }
                assayPrintSupport.setAssayResultList(assayResultList);
            }
            /**
             * 化检试剂列表
             */
            List<AssayReagent> assayReagentList = assayReagentMapper.selectList(null);
            assayPrintSupport.setAssayReagentList(assayReagentList);

        }


        return assayPrintSupport;
    }

    private void setCount(AssayPrintSupport assayPrintSupport,String assayDate){
        AssayPrintSupport aps = plasmaSamplesMapper.selectXhdbCountByAssayDate(assayDate);
        assayPrintSupport.setTotal(aps.getTotal());
        assayPrintSupport.setQualified(aps.getQualified());
        assayPrintSupport.setNotQualified(aps.getNotQualified());
        assayPrintSupport.setMaleTotal(aps.getMaleTotal());
        assayPrintSupport.setFamaleTotal(aps.getFamaleTotal());
    }
}
